#include "key.h"

#define KEY_PRESS_TIMEOUT 1000U
#define KEY_LONG_PRESS_TIMEOUT 20000U
static KeyState eKeyState = KEY_STATE_IDLE;
static uint32_t u32KeyPressStartTime = 0;   //ms
static uint32_t u32KeyPressCurTime = 0;        //ms

void KeyInit(void){

}

void KeyTask(uint8_t *u8KeyCnt){
    /*key pin - PA0 open-0 close-1*/
    switch(eKeyState){
        case KEY_STATE_IDLE:
					  u32KeyPressStartTime = HAL_GetTick();
            if (HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) == GPIO_PIN_SET) {
              HAL_Delay(20);  
							eKeyState = KEY_STATE_DEBOUNCE;
            }else{
                break;
            }
            

        case KEY_STATE_DEBOUNCE:
            if (HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) == GPIO_PIN_SET) {
                eKeyState = KEY_STATE_PRESSED;
            } else {
                eKeyState = KEY_STATE_IDLE;
                break;
            }
        case KEY_STATE_PRESSED:
            *u8KeyCnt = (*u8KeyCnt+1)%4;
            while(HAL_GetTick() - u32KeyPressStartTime < KEY_PRESS_TIMEOUT){
                if(HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) == GPIO_PIN_RESET){    
                    eKeyState = KEY_STATE_IDLE;
                    break;
                }
            }
            eKeyState = KEY_STATE_LONG_PRESSED;
        case KEY_STATE_LONG_PRESSED:
            if(HAL_GetTick() - u32KeyPressStartTime > KEY_LONG_PRESS_TIMEOUT){
                eKeyState = KEY_STATE_IDLE;
            }
            if(HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) == GPIO_PIN_RESET){
                eKeyState = KEY_STATE_IDLE;
            }
            break;
        default:
            eKeyState = KEY_STATE_IDLE;
            break;
    }
    return;
}